import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'time_ruler_widget.dart';
import '../controllers/device_detail_controller.dart';

class PlaybackMainContentWidget extends StatelessWidget {
  final DeviceDetailController controller;

  const PlaybackMainContentWidget({super.key, required this.controller});

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Column(
        children: [
          // 顶部功能栏
          _buildPlaybackTopBar(),

          // 录像内容区域
          Expanded(
            child:
                controller.isLoadingRecords.value
                    ? SizedBox(
                      height: 200.h,
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            CircularProgressIndicator(color: Color(0xFF047FF7)),
                            SizedBox(height: 20.h),
                            Text(
                              '正在加载录像数据...',
                              style: TextStyle(
                                fontSize: 28.sp,
                                color: Color(0xFF999999),
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                    : _buildContent(),
          ),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _buildContent() {
    // 如果处于下载模式，显示录像列表
    if (controller.isDownloadMode.value) {
      return _buildDownloadRecordContent();
    }

    // 云端和本地都显示时间轴
    final records =
        controller.recordSourceType.value == 'cloud'
            ? controller.recordSegments.toList()
            : controller.localRecordSegments.toList();

    return TimeRulerWidget(
      selectedTime: controller.selectedPlaybackTime.value,
      onTimeSelected: (DateTime time) {
        // 检查该时间是否有录像
        final hasRecord = _hasRecordAtTime(time, records);
        if (!hasRecord) {
          // 如果没有录像，停止当前播放器
          // 但是要避免在自动播放时调用stopCurrentVideo
          if (!controller.isLoadingPlayback.value) {
            controller.stopCurrentVideo();
          }
          return;
        }
        // 调用原来的选择时间方法
        controller.selectPlaybackTime(time);
      },
      recordSegments: records,
      isVertical: true, // 竖排显示
      selectedDate: controller.selectedPlaybackDate.value, // 传递选中的日期
    );
  }

  /// 检查指定时间是否有录像
  bool _hasRecordAtTime(DateTime time, List<Map<String, dynamic>> segments) {
    for (final segment in segments) {
      final startTime = segment['startTime'] as DateTime?;
      final endTime = segment['endTime'] as DateTime?;
      if (startTime != null && endTime != null) {
        if (time.isAfter(startTime) && time.isBefore(endTime)) {
          return true;
        }
      }
    }
    return false;
  }

  /// 构建录像回放顶部栏
  Widget _buildPlaybackTopBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.h),
      child: Row(
        children: [
          // 左侧：今日 + 日期选择
          Expanded(
            child: GestureDetector(
              onTap: () {
                _showDatePicker();
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 16.h),
                decoration: BoxDecoration(
                  color: Color(0xFFF8F9FA),
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.calendar_today_outlined,
                      size: 36.sp,
                      color: Color(0xFF047FF7),
                    ),
                    SizedBox(width: 12.w),
                    Text(
                      _isToday(controller.selectedPlaybackDate.value)
                          ? '今日'
                          : _formatDateShort(
                            controller.selectedPlaybackDate.value,
                          ),
                      style: TextStyle(
                        fontSize: 28.sp,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Icon(
                      Icons.keyboard_arrow_down,
                      size: 32.sp,
                      color: Color(0xFF999999),
                    ),
                  ],
                ),
              ),
            ),
          ),

          SizedBox(width: 254.w),

          // 右侧：功能图标组
          Row(
            children: [
              // 下载图标
              // _buildTopBarImageIcon(
              //   imagePath:
              //       controller.isDownloadMode.value
              //           ? 'assets/images/device/下载-可以点击.png'
              //           : 'assets/images/device/下载-不可点击.png',
              //   isClickable: true,
              //   onTap: () {
              //     // 跳转到视频列表页面，传递设备参数
              //     Get.toNamed(
              //       Routes.VIDEO_LIST,
              //       arguments: {
              //         'deviceId': controller.deviceId,
              //         'channelId': controller.channelId,
              //       },
              //     );
              //   },
              // ),
              // SizedBox(width: 16.w),

              // 云图标
              _buildTopBarImageIcon(
                imagePath:
                    controller.recordSourceType.value == 'cloud'
                        ? 'assets/images/device/云端-已选中.png'
                        : 'assets/images/device/云端-为选中.png',
                isClickable: true,
                onTap: () => controller.switchRecordSource('cloud'),
              ),
              SizedBox(width: 16.w),

              // 存储图标
              _buildTopBarImageIcon(
                imagePath:
                    controller.recordSourceType.value == 'local'
                        ? 'assets/images/device/存储-已选中.png'
                        : 'assets/images/device/存储-未选中.png',
                isClickable: true,
                onTap: () => controller.switchRecordSource('local'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建顶部栏图片图标
  Widget _buildTopBarImageIcon({
    required String imagePath,
    required bool isClickable,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: isClickable ? onTap : null,
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xFFF8F9FA),
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
        ),
        child: Image.asset(imagePath, width: 40, height: 40, fit: BoxFit.fill),
      ),
    );
  }

  /// 构建下载模式录像内容（录像片段列表）
  Widget _buildDownloadRecordContent() {
    final records =
        controller.recordSourceType.value == 'cloud'
            ? controller.recordSegments.toList()
            : controller.localRecordSegments.toList();

    if (records.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/null.png', width: 378.w, height: 378.w),
            SizedBox(height: 40.w),
            Text(
              '暂无录像数据',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
            ),
          ],
        ),
      );
    }

    // 按小时分组显示录像
    final groupedSegments = _groupSegmentsByHour(records);

    return ListView.builder(
      padding: EdgeInsets.all(16.w),
      itemCount: groupedSegments.keys.length,
      itemBuilder: (context, index) {
        final hour = groupedSegments.keys.elementAt(index);
        final hourSegments = groupedSegments[hour]!;
        return _buildDownloadHourGroup(hour, hourSegments);
      },
    );
  }

  /// 按小时分组录像片段
  Map<int, List<Map<String, dynamic>>> _groupSegmentsByHour(
    List<Map<String, dynamic>> segments,
  ) {
    final Map<int, List<Map<String, dynamic>>> grouped = {};

    for (final segment in segments) {
      final hour = segment['hour'] as int? ?? 0;
      if (grouped[hour] == null) {
        grouped[hour] = [];
      }
      grouped[hour]!.add(segment);
    }

    return grouped;
  }

  /// 构建下载模式小时分组
  Widget _buildDownloadHourGroup(
    int hour,
    List<Map<String, dynamic>> hourSegments,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 小时标题
        Padding(
          padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
          child: Text(
            '${hour.toString().padLeft(2, '0')}:00',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.w600,
              color: Color(0xFF333333),
            ),
          ),
        ),

        // 该小时的录像片段网格（每行3个）
        GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 0.8, // 稍微高一点的比例
          ),
          itemCount: hourSegments.length,
          itemBuilder: (context, index) {
            final segment = hourSegments[index];
            return _buildDownloadRecordItem(segment);
          },
        ),
      ],
    );
  }

  /// 构建下载模式录像项（封面+下载图标）
  Widget _buildDownloadRecordItem(Map<String, dynamic> segment) {
    final time = segment['time'] as String? ?? '';
    final duration = segment['duration'] as String? ?? '';
    final type = segment['type'] as String? ?? 'motion';

    return GestureDetector(
      onTap: () {
        controller.handleRecordDownload(segment);
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              // 录像封面背景
              segment['picUrl'] != null
                  ? Image.network(
                    segment['picUrl'],
                    width: double.infinity,
                    height: double.infinity,
                  )
                  : Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors:
                            type == 'alarm'
                                ? [
                                  Color(0xFFFF6B35),
                                  Color(0xFFFF4444),
                                ] // 告警录像用橙红色
                                : [
                                  Color(0xFF3C3C3C),
                                  Color(0xFF2C2C2C),
                                ], // 普通录像用灰色
                      ),
                    ),
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            type == 'alarm'
                                ? Icons.warning
                                : Icons.play_circle_outline,
                            size: 32.w,
                            color: Colors.white70,
                          ),
                          if (type == 'alarm')
                            Padding(
                              padding: EdgeInsets.only(top: 4.h),
                              child: Text(
                                '告警',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),

              // 时间标签
              Positioned(
                top: 8.h,
                left: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    time,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),

              // 时长标签
              Positioned(
                bottom: 8.h,
                right: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    duration,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),

              // 录像类型标签（左下角）
              if (type != 'unknown')
                Positioned(
                  bottom: 8.h,
                  left: 8.w,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 6.w,
                      vertical: 2.h,
                    ),
                    decoration: BoxDecoration(
                      color:
                          type == 'alarm'
                              ? Color(0xFFFF4444)
                              : Color(0xFF047FF7),
                      borderRadius: BorderRadius.circular(3.r),
                    ),
                    child: Text(
                      type == 'alarm' ? '告警' : '定时',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),

              // 下载图标覆盖层（居中）
              Positioned.fill(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.3),
                  ),
                  child: Center(
                    child: Container(
                      width: 48.w,
                      height: 48.w,
                      decoration: BoxDecoration(
                        color: Color(0xFF047FF7),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.download,
                        color: Colors.white,
                        size: 24.w,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 判断是否为今天
  bool _isToday(DateTime date) {
    final now = DateTime.now();
    return date.year == now.year &&
        date.month == now.month &&
        date.day == now.day;
  }

  /// 格式化日期（短格式）
  String _formatDateShort(DateTime date) {
    return '${date.month}/${date.day}';
  }

  /// 显示iOS风格的日期选择器
  void _showDatePicker() {
    DateTime tempSelectedDate = controller.selectedPlaybackDate.value;

    Get.bottomSheet(
      Container(
        height: 520.h,
        decoration: BoxDecoration(
          color: CupertinoColors.systemBackground,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              height: 100.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                color: CupertinoColors.systemBackground,
                border: Border(
                  bottom: BorderSide(
                    color: CupertinoColors.separator,
                    width: 0.5.w,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () => Get.back(),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: CupertinoColors.systemBlue,
                      ),
                    ),
                  ),
                  Text(
                    '选择录像日期',
                    style: TextStyle(
                      fontSize: 34.sp,
                      fontWeight: FontWeight.w600,
                      color: CupertinoColors.label,
                    ),
                  ),
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      controller.selectPlaybackDate(tempSelectedDate);
                      Get.back();
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: CupertinoColors.systemBlue,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // iOS风格日期选择器 - 只选择年月日
            Expanded(
              child: Container(
                color: CupertinoColors.systemBackground,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: controller.selectedPlaybackDate.value,
                  minimumDate: DateTime(2020, 1, 1),
                  maximumDate: DateTime.now(),
                  onDateTimeChanged: (DateTime date) {
                    tempSelectedDate = date;
                  },
                  dateOrder: DatePickerDateOrder.ymd, // 年-月-日顺序
                ),
              ),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }
}
